package com.xiaoyg.algorithm;

import lombok.Data;

import java.util.List;

/**
 * 翻转链表
 */
@Data
public class PalindromeList {

    static class ListNode{

        int val;
        ListNode next;

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public ListNode getNext() {
            return next;
        }

        public void setNext(ListNode next) {
            this.next = next;
        }

        public ListNode(int val, ListNode next){
            this.val = val;
            this.next = next;
        }
        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }

    }

    public static boolean isPlindrome(ListNode head){
        ListNode slow = head;
        ListNode fast = head;
        while (fast!=null && fast.next!=null){
            fast = fast.next.next;
            slow = slow.next;
        }

        //链表为奇数时，将慢指针移到最中央
        if (fast !=null){
            slow = slow.next;
        }
        //反转后半段链表
        slow = reverse(slow);
        fast = head;
        while (slow!=null){
            //结点值不想等说明是非回文链表
            if (fast.val != slow.val){
                return false;
            }
            fast = fast.next;
            slow = slow.next;
        }
        return true;
    }

    public static ListNode reverse(ListNode head){
        ListNode pre = null,next;
        //当前节点为头结点
        ListNode curr = head;
        //循环终止条件是当前节点指向空
        while (curr!=null){
            //下一个节点是当前节点的next
            next = curr.next;
            //断链，直向前一个节点
            curr.next = pre;
            pre = curr;
            curr = next;

        }
        return pre;
    }


    public static void main(String[] args) {
        ListNode node5 = new ListNode(1, null);
        ListNode node4 = new ListNode(2, node5);
        ListNode node3 = new ListNode(3, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode node1 = new ListNode(1, node2);
        System.out.println(node1);
//        ListNode iterate = iterate(node1);
        System.out.println(isPlindrome(node1));
    }

}
